package com.byx.chatclient.view.fragment.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.byx.chatclient.ChatApp;
import com.byx.chatclient.R;
import com.byx.chatclient.entity.RegisterWay;
import com.byx.chatclient.entity.Result;
import com.byx.chatclient.entity.ResultCallback;
import com.byx.chatclient.entity.UserPo;
import com.byx.chatclient.factory.ManagerFactory;
import com.byx.chatclient.factory.RetrofitFactory;
import com.byx.chatclient.http.ApiUrl;
import com.byx.chatclient.http.HttpFilesUtil;
import com.byx.chatclient.manager.UserManager;
import com.byx.chatclient.model.LoginModel;
import com.byx.chatclient.pojo.LoginDto;
import com.byx.chatclient.pojo.LoginVo;
import com.byx.chatclient.service.NettyService;
import com.byx.chatclient.utils.FileUtils;
import com.byx.chatclient.utils.ValidateUtil;
import com.byx.chatclient.view.activity.main.MainActivity;
import com.byx.chatclient.view.activity.user.RegisterActivity;
import com.byx.passwordedittext.PasswordEditText;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import soup.neumorphism.NeumorphButton;

/**
 * RegisterTwoFragment
 * 注册页2，含填写密码，确认密码，成功提交后才算注册成功
 * @author Superb
 * @date 2021/4/14 16:28
 */
public class RegisterTwoFragment extends Fragment {

    @BindView(R.id.et_password)
    protected PasswordEditText mEtPwd;
    @BindView(R.id.et_confirm_pwd)
    protected PasswordEditText mEtConfirmPwd;
    @BindView(R.id.btn_reg_two_submit)
    protected NeumorphButton mBtnRegister;

    private Unbinder unbinder;
    private LoginModel mLoginModel;
    /**
     * Called to have the fragment instantiate its user interface view.
     * This is optional, and non-graphical fragments can return null. This will be called between
     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
     * <p>A default View can be returned by calling {@link # Fragment(int)} in your
     * constructor. Otherwise, this method returns null.
     *
     * <p>It is recommended to <strong>only</strong> inflate the layout in this method and move
     * logic that operates on the returned View to {@link #onViewCreated(View, Bundle)}.
     *
     * <p>If you return a View from here, you will later be called in
     * {@link #onDestroyView} when the view is being released.
     *
     * @param inflater           The LayoutInflater object that can be used to inflate
     *                           any views in the fragment,
     * @param container          If non-null, this is the parent view that the fragment's
     *                           UI should be attached to.  The fragment should not add the view itself,
     *                           but this can be used to generate the LayoutParams of the view.
     * @param savedInstanceState If non-null, this fragment is being re-constructed
     *                           from a previous saved state as given here.
     * @return Return the View for the fragment's UI, or null.
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_register_two, container, false);
        unbinder = ButterKnife.bind(this,root);
        mLoginModel = new LoginModel(ChatApp.getInstance());
        return root;
    }

    /**
     * 点击切换到注册页
     */
    @OnClick(R.id.btn_reg_two_submit)
    public void onClick() {
        String pwd = mEtPwd.getText().toString().trim();
        String confirmPwd = mEtConfirmPwd.getText().toString().trim();
        if (!ValidateUtil.isPasswordValid(pwd)){
            Toast.makeText(requireContext(),"密码必须包含数字和字母！",Toast.LENGTH_SHORT).show();
        }else if (!confirmPwd.equals(pwd)){
            Toast.makeText(requireContext(),"两次输入的密码不一致！",Toast.LENGTH_SHORT).show();
        }else {
            String email = ((RegisterActivity) requireActivity()).getEmail();
            String encodePwd = ValidateUtil.encodeByMd5(pwd);
            long timeMillis = System.currentTimeMillis();
            RetrofitFactory.getBean(ApiUrl.class).register(email, encodePwd, timeMillis, RegisterWay.BY_EMAIL)
                    .enqueue(new ResultCallback<String>() {
                        @Override
                        public void onResultSuccess(String data) {
                            LoginVo loginVo = new LoginVo();
                            loginVo.setLoginId(data);
                            loginVo.setPassword(encodePwd);
                            loginVo.setLastModifyTime(System.currentTimeMillis());
                            login(loginVo);
                        }

                        @Override
                        public void onResultFailure(int code, String msg) {
                            Toast.makeText(RegisterTwoFragment.this.requireContext(), msg, Toast.LENGTH_LONG).show();
                        }
                    });
        }
    }

    private void login(LoginVo loginVo){
        RetrofitFactory.getBean(ApiUrl.class).login(loginVo)
                .enqueue(new ResultCallback<LoginDto>() {
                    @Override
                    public void onResultSuccess(LoginDto data) {
                        final boolean[] flag = {false};
                        if (data != null){
                            UserPo userPo = mLoginModel.queryUserPoById(loginVo.getLoginId());
                            //如果服务端返回的用户信息不为空，说明数据不一致，需要更新，则保存用户信息，密码通过Base64加密保存
                            if (userPo == null || userPo.getLocalAvatarUrl() == null ||
                                    !data.getAvatar().equals(userPo.getRemoteAvatarUrl()) ||
                                    !FileUtils.isFileExists(userPo.getLocalAvatarUrl())) {
                                String path = ChatApp.getInstance().getExternalFilesDir(null).getAbsolutePath() + "/avatar";
                                if (FileUtils.createOrExistsDir(path)){
                                    flag[0] = true;
                                    String name = data.getAvatar();
                                    String finalName = path + name.substring(name.lastIndexOf('/'));
                                    HttpFilesUtil.download(finalName, name, new HttpFilesUtil.DownloadCallBack() {
                                        @Override
                                        public void onSuccess() {
                                            mLoginModel.saveLoginInfo(data,ValidateUtil.encodeByBase64(loginVo.getPassword()), finalName);
                                            success(loginVo.getLoginId());
                                        }

                                        @Override
                                        public void onFailure(Throwable t) {

                                        }
                                    });
                                }
                            }else {
                                mLoginModel.saveLoginInfo(data,ValidateUtil.encodeByBase64(loginVo.getPassword()),userPo.getLocalAvatarUrl());
                            }
                        }
                        if (!flag[0]){
                            success(loginVo.getLoginId());
                        }
                    }

                    @Override
                    public void onResultFailure(int code, String msg) {

                    }
                });
    }

    private void success(String loginId){
        //从本地数据库中取出用户信息，缓存在内存
        UserPo userPo = mLoginModel.queryUserPoById(loginId);
        ChatApp.getInstance().saveCurrentUser(userPo);
        //开启服务
        requireActivity().startService(new Intent(requireContext(), NettyService.class));
        startActivity(new Intent(requireContext(),MainActivity.class));
        requireActivity().finish();
    }

    /**
     * Called when the view previously created by {@link #onCreateView} has
     * been detached from the fragment.  The next time the fragment needs
     * to be displayed, a new view will be created.  This is called
     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
     * <em>regardless</em> of whether {@link #onCreateView} returned a
     * non-null view.  Internally it is called after the view's state has
     * been saved but before it has been removed from its parent.
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
